package com.phkj.qdh.ui.fragment.drafts

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.RequiresApi
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter4.QuickAdapterHelper
import com.google.gson.reflect.TypeToken
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.hjq.toast.ToastUtils
import com.lxj.xpopup.XPopup
import com.phkj.qdh.R
import com.phkj.qdh.bean.BaseDraftBean
import com.phkj.qdh.bean.BaseInspectBean
import com.phkj.qdh.bean.DeptUserVo
import com.phkj.qdh.bean.Detail
import com.phkj.qdh.bean.DraftBean
import com.phkj.qdh.bean.FileUploadBean
import com.phkj.qdh.bean.KeyPointData
import com.phkj.qdh.bean.KeyPointDataBean
import com.phkj.qdh.bean.TeamScoreBean
import com.phkj.qdh.databinding.FragmentBaseInspectSubmitBinding
import com.phkj.qdh.databinding.FragmentDraftBaseBinding
import com.phkj.qdh.databinding.FragmentDraftLawBinding
import com.phkj.qdh.net.FILE_UPLOAD
import com.phkj.qdh.net.msg
import com.phkj.qdh.ui.adapter.BaseInspectDetailAdapter
import com.phkj.qdh.ui.adapter.CommonSelectBean
import com.phkj.qdh.ui.adapter.ImagerViewAdapter
import com.phkj.qdh.ui.adapter.ImagerViewAddAdapter
import com.phkj.qdh.ui.dialog.BaseInspectTreeSelectDialog
import com.phkj.qdh.ui.dialog.CommonConfirmDialog
import com.phkj.qdh.ui.dialog.CommonConfirmListener
import com.phkj.qdh.ui.dialog.CommonSelectDialog
import com.phkj.qdh.ui.dialog.CommonSelectSingleListener
import com.phkj.qdh.ui.dialog.EmployeeSelectDialog
import com.phkj.qdh.ui.dialog.EmployeeSelectListener
import com.phkj.qdh.ui.dialog.SelectBaseSortListener
import com.phkj.qdh.ui.dialog.SelectKeyPonitDialog
import com.phkj.qdh.ui.fragment.teaminspect.TeamInspectVM
import com.phkj.qdh.ui.fragment.teaminspect.getTeamInspectVMProvider
import com.phkj.qdh.utils.FileHelper
import com.phkj.qdh.utils.GetImgContract
import com.phkj.qdh.utils.LogUtil
import com.phkj.qdh.utils.MyItemDecoration
import com.phkj.qdh.utils.SPSUtils
import com.phkj.qdh.utils.SPS_DRAFTS
import com.phkj.qdh.utils.TakePhoto
import com.phkj.qdh.utils.launchAndRepeatWithViewLifecycle
import com.phkj.qdh.utils.requestMain
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collectLatest
import rxhttp.wrapper.utils.GsonUtil
import rxhttp3.RxHttp
import rxhttp3.toFlowResponse
import java.io.File
import java.text.SimpleDateFormat
import java.util.GregorianCalendar
import java.util.Locale

private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * 草稿基础巡查
 */
class DraftBaseFragment : Fragment() {
    private var param1: BaseInspectBean? = null
    private var param2: Int? = null
    private var data: BaseDraftBean? = null
    private var _binding: FragmentDraftBaseBinding? = null
    private lateinit var vm: TeamInspectVM
    private val binding get() = _binding!!
    private var imageUri: Uri? = null
    private var filePath: String = ""
    private val iVAdapter by lazy { ImagerViewAdapter() }
    private val iVAddAdapter by lazy { ImagerViewAddAdapter() }
    private var rectification: Int? = null //0需要整改，1不需要整改
    private var anyRisk: Int? = null  //0有风险，1无风险
    private var eventScoreConfigurationId: Int? = null  //0有风险，1无风险
    private val baseInspectDetailAdapter by lazy { BaseInspectDetailAdapter() }
    private var eventScoreConfigurationBean: TeamScoreBean? = null  //0有风险，1无风险
    private var lastKeyPointTypeId: Int? = null
    private var second: Int? = null
    private var secondBean: BaseInspectBean? = null
    private var keyPointDataBean: KeyPointData? = null
    private var userIds = ArrayList<Int>()
    private var policyIds = ArrayList<Int>()
    private val takePic =
        registerForActivityResult(ActivityResultContracts.TakePicture()) { boolean ->
            if (boolean) {
                try {
                    imageUri?.let { uri ->
                        val option = BitmapFactory.Options()
                        option.inPreferredConfig = Bitmap.Config.RGB_565
                        val bitmap = BitmapFactory.decodeStream(
                            requireContext().contentResolver.openInputStream(uri), null, option
                        )
                        val yasuohou = TakePhoto.scaleBitmap(bitmap, 0.5f)
                        val path = TakePhoto.saveBitmap2File(yasuohou)
                        uploadImg(path)
                    }

                } catch (e: Exception) {

                }

            }
        }

    private val selectImg = registerForActivityResult(GetImgContract()) { uri ->
        uri?.let {
            LogUtil.E(it.toString())
            val file = FileHelper.getFileAbsolutePath(requireContext(), it)
            uploadImg(file)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            data = it.getParcelable(ARG_PARAM1)
            param2 = it.getInt(ARG_PARAM2)
        }
        parentFragmentManager.setFragmentResultListener("key", this) { req, bnundle ->
            val data = bnundle.getParcelable<KeyPointData>("data")
            data?.let {
                baseInspectDetailAdapter.submitList(it.keyPointFieldBaseVOList)
                keyPointDataBean = it
            }
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentDraftBaseBinding.inflate(inflater, container, false)
        vm = ViewModelProvider(this, getTeamInspectVMProvider())[TeamInspectVM::class.java]
        return binding.root

    }

    @RequiresApi(Build.VERSION_CODES.N)
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        param1 = data?.headBean!!
        data?.let {
            lastKeyPointTypeId = it.lastKeyPointTypeId
            second = it.secondPos
            secondBean = it.secondBean
            binding.tvSort1.text = secondBean?.name ?: ""
            it.keyPointDataBean?.let { key ->
                keyPointDataBean = key
                baseInspectDetailAdapter.submitList(key.keyPointFieldBaseVOList)
            }
            it.anyRisk?.let { risk ->
                anyRisk = risk
                if (risk == 0) {
                    binding.tvRisk.text = "有"
                } else {
                    binding.tvRisk.text = "无"
                }
            }
            it.rectification.let { a ->
                rectification = a
                if (a == 1) {
                    binding.tvState.text = "已整改"
                } else {
                    binding.tvState.text = "未整改"
                }
            }
            binding.edtRemark.setText(it.remark ?: "")
            iVAdapter.submitList(it.imgList)
            it.userId?.let { it1 -> userIds.addAll(it1) }
            binding.tvMingjing.text = it.tvUser
            eventScoreConfigurationBean = it.eventScoreConfigurationBean
            eventScoreConfigurationId = it.eventScoreConfigurationBean?.id
            binding.tvBanFa.text = eventScoreConfigurationBean?.name ?: ""
            binding.tvFen.text = "${eventScoreConfigurationBean?.score ?: ""}"
        }
        binding.run {
            tvFiestName.text = param1?.name
            tvSort1.hint = "请选择${param1?.name}类型"
            rlTonggao.setOnClickListener {
                val dialog = BaseInspectTreeSelectDialog(
                    requireContext(), param1?.childrenList as ArrayList<BaseInspectBean>
                )
                dialog.setSelectSortListener(object : SelectBaseSortListener {
                    override fun ok(data: Pair<BaseInspectBean?, BaseInspectBean?>) {
                        if (data.second != null) {
                            secondBean = data.second
                            tvSort1.text = data.second?.name
                            lastKeyPointTypeId = data.second?.id
                        } else {
                            secondBean = data.first
                            tvSort1.text = data.first?.name
                            lastKeyPointTypeId = data.first?.id
                        }

                    }
                })
                dialog.setTitle("${param1?.name}问题")

                XPopup.Builder(requireContext()).dismissOnTouchOutside(true).asCustom(dialog).show()
            }
            rvDetail.run {
                layoutManager = LinearLayoutManager(requireContext())
                adapter = baseInspectDetailAdapter
            }
            btnCaogao.setOnClickListener {
                val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                val baseDraftBean = BaseDraftBean(
                    param1,
                    secondBean,
                    second,
                    lastKeyPointTypeId,
                    keyPointDataBean,
                    anyRisk,
                    rectification,
                    binding.edtRemark.text.toString(),
                    iVAdapter.items,
                    userIds,
                    binding.tvMingjing.text.toString(),
                    eventScoreConfigurationBean,
                    dateFormat.format(System.currentTimeMillis())
                )
                try {
                    val localDraft = GsonUtil.fromJson<ArrayList<DraftBean>>(
                        SPSUtils.getString(
                            SPS_DRAFTS, ""
                        ), object : TypeToken<ArrayList<DraftBean>>() {}.type
                    )
                    localDraft.add(0, DraftBean(localDraft.size + 1, 1, baseDraftBean, null, null))
                    SPSUtils.put(SPS_DRAFTS, GsonUtil.toJson(localDraft))
                } catch (e: Exception) {
                    e.printStackTrace()
                    SPSUtils.put(
                        SPS_DRAFTS,
                        GsonUtil.toJson(arrayListOf(DraftBean(0, 1, baseDraftBean, null, null)))
                    )
                }
                ToastUtils.show("已保存为草稿")
                parentFragmentManager.popBackStack(
                    "draft", FragmentManager.POP_BACK_STACK_INCLUSIVE
                )

            }
            llThird.setOnClickListener {
                if (binding.tvSort1.text.toString().isBlank()) {
                    ToastUtils.show("请先选择${param1?.name}类型")
                    return@setOnClickListener
                }
                val dialog = SelectKeyPonitDialog.newInstance(
                    secondBean?.id ?: 0, binding.tvFiestName.text.toString()
                )
                dialog.show(parentFragmentManager, "")
            }
            rvBaseSubmit.run {
                layoutManager =
                    LinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL, false)
                addItemDecoration(
                    MyItemDecoration(
                        ContextCompat.getColor(requireContext(), R.color.transparent),
                        28,
                        RecyclerView.HORIZONTAL
                    )
                )
            }
            ivBack.setOnClickListener {
                parentFragmentManager.popBackStack()
            }
            rlZerren.setOnClickListener {
                vm.getEmployee1()
            }
            llMingjing.setOnClickListener {
                vm.getEmployee()
            }
            llHasRisk.setOnClickListener {
                val dialog = CommonConfirmDialog.getInstance("风险隐患", "有无风险隐患", "有", "无")
                dialog.setCancelListener(object : CommonConfirmListener {
                    override fun dOk() {
                        tvRisk.text = "有"
                        anyRisk = 0
                    }

                    override fun dCancel() {
                        anyRisk = 1
                        tvRisk.text = "无"
                    }
                })
                dialog.show(parentFragmentManager, "")
            }
            rlBanfa.setOnClickListener {
                vm.getBaseScoreList(1)
            }
            llZhenggai.setOnClickListener {
                val dialog =
                    CommonConfirmDialog.getInstance("整改情况", "是否已整改", "已整改", "未整改")
                dialog.setCancelListener(object : CommonConfirmListener {
                    override fun dOk() {
//                        llDate.gone()
//                        tvDate.text = ""
                        tvState.text = "已整改"
                        rectification = 1
                    }

                    override fun dCancel() {
//                        llDate.visible()
                        rectification = 0
                        tvState.text = "未整改"
                    }
                })
                dialog.show(parentFragmentManager, "")
            }
            btnOk.setOnClickListener {
                if (lastKeyPointTypeId == null) {
                    ToastUtils.show("请选择行业类型")
                    return@setOnClickListener
                }
                if (anyRisk == null) {
                    ToastUtils.show("请选择有无风险隐患")
                    return@setOnClickListener
                }
                if (eventScoreConfigurationId == null) {
                    ToastUtils.show("请选择处置办法")
                    return@setOnClickListener
                }
                if (iVAdapter.items.isEmpty()) {
                    ToastUtils.show("请上传照片")
                    return@setOnClickListener
                }

                if (userIds.isEmpty()) {
                    ToastUtils.show("请选择检查民警")
                    return@setOnClickListener
                }

                val dialog = CommonConfirmDialog.getInstance("提交", "确定要提交吗")
                dialog.setCancelListener(object : CommonConfirmListener {
                    override fun dOk() {
                        val map = HashMap<String, Any?>()
                        map["keyPointTypeId"] = param1?.id
                        map["lastKeyPointTypeId"] = lastKeyPointTypeId
                        map["keyPointDataId"] = keyPointDataBean?.id
                        map["anyRisk"] = anyRisk
                        map["eventType"] = 1
                        map["imageUrl"] =
                            iVAdapter.items.toString().replace(",", "").replace("[", "")
                                .replace("]", "")
                        map["rectification"] = rectification
                        map["remark"] = binding.edtRemark.text.toString()
                        map["stateName"] = binding.tvState.text.toString()
                        map["eventScoreConfigurationId"] = eventScoreConfigurationId
                        map["userIds"] = userIds
                        vm.baseInspectSave(map)
                    }

                    override fun dCancel() {}
                })
                dialog.show(parentFragmentManager, "")


            }
        }


        val helper = QuickAdapterHelper.Builder(iVAdapter).build()
        helper.addBeforeAdapter(iVAddAdapter)
        iVAddAdapter.add("s")
        binding.rvBaseSubmit.adapter = helper.adapter
        iVAdapter.addOnItemChildClickListener(R.id.iv_delete) { adapter, _, pos ->
            val dialog = CommonConfirmDialog.getInstance(
                "删除图片", "确定要删除图片吗", "确定", "取消"
            )
            dialog.setCancelListener(object : CommonConfirmListener {
                override fun dOk() {
                    adapter.removeAt(pos)
                }

                override fun dCancel() {
                    takePhoto()
                }

            })
            dialog.show(parentFragmentManager, "")
        }

        iVAddAdapter.setOnItemClickListener { adapter, data, pos ->
            if (iVAdapter.items.size >= 6) {

                ToastUtils.show("图片数量不能超过6张")
                return@setOnItemClickListener

            }
            XXPermissions.with(requireContext())
                .permission(arrayListOf(Permission.READ_MEDIA_IMAGES, Permission.CAMERA))
                .request(object : OnPermissionCallback {
                    override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                        if (allGranted) {
                            val dialog = CommonConfirmDialog.getInstance(
                                "上传图片", "请选择上传方式", "选择照片", "拍照"
                            )
                            dialog.setCancelListener(object : CommonConfirmListener {
                                override fun dOk() {
                                    selectImg.launch(null)
                                }

                                override fun dCancel() {
                                    takePhoto()
                                }

                            })
                            dialog.show(parentFragmentManager, "")
                        }
                    }

                    override fun onDenied(
                        permissions: MutableList<String>, doNotAskAgain: Boolean
                    ) {
                        super.onDenied(permissions, doNotAskAgain)
                    }
                })
        }

        launchAndRepeatWithViewLifecycle {
            vm.baseInspectSave.collectLatest {
                if (it == 0) {
                    ToastUtils.show("提交成功")
                    try {
                        val json = SPSUtils.getString(SPS_DRAFTS, "")
                        val data = GsonUtil.fromJson<ArrayList<DraftBean>>(
                            json, object : TypeToken<ArrayList<DraftBean>>() {}.type
                        )
                        param2?.let { id ->
                            data.removeIf { d -> d.id == id }
                        }
                        SPSUtils.put(SPS_DRAFTS, GsonUtil.toJson(data))
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                    parentFragmentManager.popBackStack(
                        "draft", FragmentManager.POP_BACK_STACK_INCLUSIVE
                    )
                }
            }
        }

        launchAndRepeatWithViewLifecycle {
            vm.employee.collectLatest {
                // 选择审批人
                val dialog = EmployeeSelectDialog(requireContext(), it)
                dialog.setListener(object : EmployeeSelectListener {
                    override fun ok(list: ArrayList<DeptUserVo>) {
                        val sb = StringBuilder()
                        userIds.clear()
                        list.forEach { bean ->
                            sb.append(bean.userNamePhone)
                            sb.append("\n")
                            userIds.add(bean.userId)
                        }
                        binding.tvMingjing.text =
                            if (sb.length > 1) sb.deleteCharAt(sb.length - 1).toString() else ""
                    }
                })
                XPopup.Builder(requireContext()).asCustom(dialog).show()
            }
        }


        launchAndRepeatWithViewLifecycle {
            vm.employee1.collectLatest {
                // 选择审批人
                val dialog = EmployeeSelectDialog(requireContext(), it)
                dialog.setListener(object : EmployeeSelectListener {
                    override fun ok(list: ArrayList<DeptUserVo>) {
                        val sb = StringBuilder()
                        policyIds.clear()
                        list.forEach { bean ->
                            sb.append(bean.userNamePhone)
                            sb.append("\n")
                            policyIds.add(bean.userId)
                        }
                        binding.tvZeren.text =
                            if (sb.length > 1) sb.deleteCharAt(sb.length - 1).toString() else ""
                    }
                })
                XPopup.Builder(requireContext()).asCustom(dialog).show()
            }
        }

        launchAndRepeatWithViewLifecycle {
            vm.baseScoreList.collectLatest {
                val showList = it.map { score -> CommonSelectBean(score.name) } as ArrayList
                val dialog = CommonSelectDialog(requireContext(), showList, true)
                dialog.setTitle("处置办法")
                dialog.setUnSelectTips("请选择一个处置办法")
                dialog.setSingleResultListener(object : CommonSelectSingleListener {
                    override fun ok(pos: Int) {
                        binding.tvBanFa.text = it[pos].name
                        binding.tvFen.text = it[pos].score.toString()
                        eventScoreConfigurationId = it[pos].id
                        eventScoreConfigurationBean = it[pos]
                    }
                })
                XPopup.Builder(requireContext()).dismissOnTouchOutside(true).asCustom(dialog).show()

            }
        }
    }


    private fun takePhoto() {
        val simpleDate = SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault())
        val fileName = simpleDate.format(GregorianCalendar().time) + ".jpg"
        var outputImage = File(requireContext().externalCacheDir, fileName)
        if (outputImage.exists()) {
            outputImage.delete()
        }
        outputImage.createNewFile()
        imageUri = if (Build.VERSION.SDK_INT >= 24) {
            FileProvider.getUriForFile(
                requireContext(), "com.phkj.qdh.fileprovider", outputImage
            )
        } else {
            Uri.fromFile(outputImage)
        }
        filePath = outputImage.absolutePath
        takePic.launch(imageUri)

    }

    private fun uploadImg(path: String) {
        requestMain {
            RxHttp.postForm(FILE_UPLOAD).addFile("file", path).toFlowResponse<FileUploadBean>()
                .catch { cause ->
                    ToastUtils.show(cause.msg)
                }.collectLatest {
                    delay(500)
                    iVAdapter.add(it.url)
                }
        }
    }

    companion object {
        @JvmStatic
        fun newInstance(param1: BaseDraftBean, param2: Int) = DraftBaseFragment().apply {
            arguments = Bundle().apply {
                putParcelable(ARG_PARAM1, param1)
                putInt(ARG_PARAM2, param2)
            }
        }
    }
}